import logger from '../utils/logger.js'

/**
 * 本地存储管理工具
 * 用于保存和管理用户创建的题目信息
 */

const STORAGE_KEYS = {
  MY_QUESTIONS: 'my_questions_local',
  QUESTION_COUNTER: 'question_counter'
};

/**
 * 本地存储的题目管理器
 */
class LocalQuestionStorage {
  constructor() {
    this.userId = this.getCurrentUserId();
    this.storageKey = `${STORAGE_KEYS.MY_QUESTIONS}_${this.userId}`;
    this.counterKey = `${STORAGE_KEYS.QUESTION_COUNTER}_${this.userId}`;
  }

  /**
   * 获取当前用户ID
   */
  getCurrentUserId() {
    try {
      // 从JWT令牌解析用户ID
      const token = localStorage.getItem('token');
      if (token) {
        const tokenParts = token.split('.');
        if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]));
          const jwtUserId = payload.claims?.id;
          if (jwtUserId) {
            return String(jwtUserId); // 确保字符串格式
          }
        }
      }
      
      // 备选方案：从localStorage获取
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        return String(userInfo.id || '1953810929896525824');
      }
    } catch (error) {
      logger.error('❌ [LocalStorage] 获取用户ID失败:', error);
    }
    return '1953810929896525824'; // 默认用户ID
  }

  /**
   * 生成新的题目ID (5位数格式，适配后端要求)
   */
  generateQuestionId() {
    let counter = parseInt(localStorage.getItem(this.counterKey) || '10000');
    counter++;
    
    // 确保counter在5位数范围内 (10000-99999)
    if (counter > 99999) {
      counter = 10000; // 重置到起始值
    }
    
    localStorage.setItem(this.counterKey, String(counter));
    
    logger.log('🆔 [LocalStorage] 生成新的5位数题目ID:', counter);
    return counter; // 直接返回5位数字
  }

  /**
   * 保存题目到本地存储
   */
  saveQuestion(questionData) {
    try {
      logger.log('💾 [LocalStorage] 保存题目到本地存储:', questionData);
      
      const questions = this.getAllQuestions();
      
      // 为新题目生成ID和时间戳
      const newQuestion = {
        ...questionData,
        id: this.generateQuestionId(),
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        source: 'local' // 标记为本地创建
      };
      
      questions.push(newQuestion);
      localStorage.setItem(this.storageKey, JSON.stringify(questions));
      
      logger.log('✅ [LocalStorage] 题目保存成功，ID:', newQuestion.id);
      return newQuestion;
    } catch (error) {
      logger.error('❌ [LocalStorage] 保存题目失败:', error);
      throw new Error('保存题目到本地失败');
    }
  }

  /**
   * 获取所有本地题目
   */
  getAllQuestions() {
    try {
      const questionsStr = localStorage.getItem(this.storageKey);
      if (questionsStr) {
        const questions = JSON.parse(questionsStr);
        logger.log('📖 [LocalStorage] 从本地加载题目数量:', questions.length);
        return Array.isArray(questions) ? questions : [];
      }
    } catch (error) {
      logger.error('❌ [LocalStorage] 加载本地题目失败:', error);
    }
    return [];
  }

  /**
   * 根据ID获取题目
   */
  getQuestionById(questionId) {
    const questions = this.getAllQuestions();
    
    // 处理不同类型的ID比较
    return questions.find(q => {
      // 尝试字符串匹配
      if (q.id === questionId) return true;
      
      // 尝试数字匹配
      if (Number(q.id) === Number(questionId)) return true;
      
      // 对于长ID，提取最后5位进行匹配
      if (typeof questionId === 'string' && questionId.length > 5) {
        const numericPart = questionId.replace(/\D/g, '');
        if (numericPart.length >= 5) {
          const shortId = parseInt(numericPart.slice(-5));
          if (Number(q.id) === shortId) return true;
        }
      }
      
      return false;
    });
  }

  /**
   * 更新题目
   */
  updateQuestion(questionId, updateData) {
    try {
      const questions = this.getAllQuestions();
      
      // 使用与getQuestionById相同的匹配逻辑
      const index = questions.findIndex(q => {
        // 尝试字符串匹配
        if (q.id === questionId) return true;
        
        // 尝试数字匹配
        if (Number(q.id) === Number(questionId)) return true;
        
        // 对于长ID，提取最后5位进行匹配
        if (typeof questionId === 'string' && questionId.length > 5) {
          const numericPart = questionId.replace(/\D/g, '');
          if (numericPart.length >= 5) {
            const shortId = parseInt(numericPart.slice(-5));
            if (Number(q.id) === shortId) return true;
          }
        }
        
        return false;
      });
      
      if (index === -1) {
        logger.error('❌ [LocalStorage] 题目不存在，ID:', questionId);
        throw new Error('题目不存在');
      }
      
      questions[index] = {
        ...questions[index],
        ...updateData,
        // 保持原始ID不变，除非明确指定新ID
        id: updateData.id || questions[index].id,
        updateTime: new Date().toISOString()
      };
      
      localStorage.setItem(this.storageKey, JSON.stringify(questions));
      logger.log('✅ [LocalStorage] 题目更新成功，原ID:', questionId, '匹配到的题目ID:', questions[index].id);
      return questions[index];
    } catch (error) {
      logger.error('❌ [LocalStorage] 更新题目失败:', error);
      throw error;
    }
  }

  /**
   * 同步后端题目数据到本地存储
   * 用于保存从后端获取的真实题目数据，保持真实ID
   */
  syncQuestionFromBackend(questionData) {
    try {
      logger.log('🔄 [LocalStorage] 同步后端题目数据:', questionData);
      
      const questions = this.getAllQuestions();
      
      // 查找是否已存在此题目（通过题目名称匹配）
      const existingIndex = questions.findIndex(q => 
        q.questionName === questionData.questionName
      );
      
      const syncedQuestion = {
        ...questionData,
        updateTime: new Date().toISOString(),
        source: 'backend' // 标记为后端数据
      };
      
      if (existingIndex !== -1) {
        // 更新现有题目，保持后端的真实ID
        logger.log('🔄 [LocalStorage] 更新现有题目，使用后端ID:', questionData.id);
        questions[existingIndex] = syncedQuestion;
      } else {
        // 添加新题目
        logger.log('➕ [LocalStorage] 添加新题目，使用后端ID:', questionData.id);
        syncedQuestion.createTime = new Date().toISOString();
        questions.push(syncedQuestion);
      }
      
      localStorage.setItem(this.storageKey, JSON.stringify(questions));
      logger.log('✅ [LocalStorage] 后端数据同步成功');
      
      return syncedQuestion;
    } catch (error) {
      logger.error('❌ [LocalStorage] 同步后端数据失败:', error);
      throw error;
    }
  }

  /**
   * 删除题目
   */
  deleteQuestion(questionId) {
    try {
      const questions = this.getAllQuestions();
      const filteredQuestions = questions.filter(q => q.id !== questionId);
      
      if (filteredQuestions.length === questions.length) {
        throw new Error('题目不存在');
      }
      
      localStorage.setItem(this.storageKey, JSON.stringify(filteredQuestions));
      logger.log('✅ [LocalStorage] 题目删除成功:', questionId);
      return true;
    } catch (error) {
      logger.error('❌ [LocalStorage] 删除题目失败:', error);
      throw error;
    }
  }

  /**
   * 批量删除题目
   */
  deleteQuestions(questionIds) {
    try {
      const questions = this.getAllQuestions();
      const filteredQuestions = questions.filter(q => !questionIds.includes(q.id));
      
      localStorage.setItem(this.storageKey, JSON.stringify(filteredQuestions));
      const deletedCount = questions.length - filteredQuestions.length;
      logger.log('✅ [LocalStorage] 批量删除题目成功，删除数量:', deletedCount);
      return deletedCount;
    } catch (error) {
      logger.error('❌ [LocalStorage] 批量删除题目失败:', error);
      throw error;
    }
  }

  /**
   * 搜索和筛选题目
   */
  searchQuestions(searchParams = {}) {
    try {
      let questions = this.getAllQuestions();
      
      // 关键词搜索
      if (searchParams.keyword) {
        const keyword = searchParams.keyword.toLowerCase();
        questions = questions.filter(q => 
          q.questionName?.toLowerCase().includes(keyword) ||
          q.questionDescribe?.toLowerCase().includes(keyword)
        );
      }
      
      // 难度筛选
      if (searchParams.difficulty) {
        questions = questions.filter(q => q.difficulty === Number(searchParams.difficulty));
      }
      
      // 类型筛选
      if (searchParams.type) {
        questions = questions.filter(q => q.questionType === Number(searchParams.type));
      }
      
      // 公开状态筛选
      if (searchParams.isPublic !== undefined && searchParams.isPublic !== '') {
        questions = questions.filter(q => q.isPublic === Number(searchParams.isPublic));
      }
      
      // 排序
      if (searchParams.sortBy) {
        switch (searchParams.sortBy) {
          case 'createTime':
            questions.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
            break;
          case 'difficulty':
            questions.sort((a, b) => (b.difficulty || 1) - (a.difficulty || 1));
            break;
          case 'submissionQuantity':
            questions.sort((a, b) => (b.submissionQuantity || 0) - (a.submissionQuantity || 0));
            break;
          case 'byQuantity':
            questions.sort((a, b) => (b.byQuantity || 0) - (a.byQuantity || 0));
            break;
        }
      }
      
      logger.log('🔍 [LocalStorage] 搜索结果数量:', questions.length);
      return questions;
    } catch (error) {
      logger.error('❌ [LocalStorage] 搜索题目失败:', error);
      return [];
    }
  }

  /**
   * 获取分页数据
   */
  getPagedQuestions(searchParams = {}, page = 1, pageSize = 12) {
    const allQuestions = this.searchQuestions(searchParams);
    const total = allQuestions.length;
    const totalPages = Math.ceil(total / pageSize);
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const questions = allQuestions.slice(startIndex, endIndex);
    
    return {
      questions,
      total,
      totalPages,
      currentPage: page,
      pageSize
    };
  }

  /**
   * 清空所有本地题目
   */
  clearAllQuestions() {
    try {
      localStorage.removeItem(this.storageKey);
      localStorage.removeItem(this.counterKey);
      logger.log('🗑️ [LocalStorage] 已清空所有本地题目');
    } catch (error) {
      logger.error('❌ [LocalStorage] 清空本地题目失败:', error);
    }
  }

  /**
   * 导出题目数据
   */
  exportQuestions() {
    const questions = this.getAllQuestions();
    const exportData = {
      userId: this.userId,
      exportTime: new Date().toISOString(),
      questionsCount: questions.length,
      questions
    };
    
    return JSON.stringify(exportData, null, 2);
  }

  /**
   * 导入题目数据
   */
  importQuestions(jsonData) {
    try {
      const importData = JSON.parse(jsonData);
      if (importData.questions && Array.isArray(importData.questions)) {
        localStorage.setItem(this.storageKey, JSON.stringify(importData.questions));
        logger.log('📥 [LocalStorage] 导入题目成功，数量:', importData.questions.length);
        return importData.questions.length;
      } else {
        throw new Error('无效的导入数据格式');
      }
    } catch (error) {
      logger.error('❌ [LocalStorage] 导入题目失败:', error);
      throw error;
    }
  }
}

// 创建全局实例
const localQuestionStorage = new LocalQuestionStorage();

// 导出管理器实例和类
export default localQuestionStorage;
export { LocalQuestionStorage }; 